package com.atguigu.gulimall.order.listener;


import com.atguigu.common.to.mq.MqMessage;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.MqMessageService;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;


@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @Autowired
    MqMessageService mqMessageService;


    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        System.out.println("过期订单， 准备关闭。。。");
        try {
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            String string = new String(message.getBody());
            System.out.println("记录MQ 的日志 , string=" + string);
            MqMessage mqMessage = new MqMessage();
            mqMessage.setMessageId(orderEntity.getMqMessageId());
            mqMessage.setMessageStatus(3);  // 已抵达
            mqMessage.setUpdateTime(new Date());
            mqMessageService.updateById(mqMessage);
        }catch (Exception e){
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
